<?php

namespace app\hook;


use app\modules\Admin\models\pickgoodscardModel;
use app\modules\Admin\models\scoregoodsModel;
use app\service\member;
use Illuminate\Database\Capsule\Manager as DB;

class orderpayed
{
    public function after($params = [])
    {
        \Log::out('orderpayed after ' . json_encode($params), 'pay');
        // 订单支付成功
        $order = $params['order'];
        $notify = $params['notify'];

        // 更新订单支付状态，记录支付回调数据
        $order->status = \orderModel::STATUS_PAYED;
        $order->paytime = time();
        $order->transaction_id = $notify['transaction_id'];
        $order->payment_json = json_encode($notify);
        $order->pay_type = $notify['pay_type'] ?? '';
        $order->save();
        $user = \memberModel::find($order->member_id);
        \orderactionModel::operAdd($order, null, $user, 'user', '用户支付成功');

        // 重新查询订单
        $order = \orderModel::query()->with('item')->find($order['id']);

        // 积分商城能量商品扣除积分
        if ($order['type'] == 'score' && $order->score_fee > 0) {
            \memberModel::score(
                -$order->score_fee,
                $order->member_id,
                'orderpay',
                $order->id,
                "积分商品支付积分 订单编号{$order->order_sn}"
            );
        }

        // 如果是套餐订单，检查套餐中是否有提货卡
        $order_ext = json_decode($order->getRawOriginal('ext'), true);
        if (!empty($order_ext['combo'])) {
            $order_item = \orderitemModel::where('order_id', $order->id)->first();
            $goods_combo = json_decode($order_item->getRawOriginal('goods_combo'), true);
            if ($goods_combo['card']) {
                $cards = pickgoodscardModel::whereIn('id', array_column($goods_combo['card'], 'card_id'))->get();
                foreach ($goods_combo['card'] as $goods_combo_card_item) {
                    foreach ($cards as $card) {
                        if ($card->id == $goods_combo_card_item['card_id']) {
                            break;
                        }
                    }
                    $expire = null;
                    if (!empty($card['card_valid_day'])) {
                        $expire = date('Y-m-d H:i:s', strtotime("+ {$card['card_valid_day']} day"));
                    }
                    if (!empty($card['card_validtime_end'])) {
                        $expire = $card['card_validtime_end'];
                    }
                    for ($i = 0; $i < $goods_combo_card_item['card_num']; $i++) {
                        $card_sn = uniqid();
                        $card_sn = preg_replace('/[a-z]/', mt_rand(0, 9), $card_sn);
                        $card_sn = preg_replace('/[A-Z]/', mt_rand(0, 9), $card_sn);
                        $member_card[] = [
                            'card_sn' => $card_sn,
                            'card_id' => $card['id'],
                            'member_id' => $order->member_id,
                            'money' => $card['amount'],
                            'expire' => $expire,
                            'created_at' => date('Y-m-d H:i:s'),
                        ];
                    }
                }
            }
            if (!empty($member_card)) {
                DB::table('member_pickgoods_card')->insert($member_card);
            }
        }

        // 商品如果设置赠送积分增加用户积分
        $orderItemList = \orderitemModel::where('order_id', $order->id)->get();
        $orderItemSkuPriceIds = [];
        foreach ($orderItemList as $orderItemItem) {
            $orderItemSkuPriceIds[] = $orderItemItem->goods_sku_price_id;
        }
        $orderItemSkuPrice = \goodsskupriceModel::whereIn('id', $orderItemSkuPriceIds)->get();
        $give_score = 0;
        $people     = 0;
        if (!empty($order_ext['combo'])) {
//            $give_score = \goodsskupriceModel::where('id', $orderItemSkuPriceIds[0])->value('score');
            $goods_sku = \goodsskupriceModel::where('id', $orderItemSkuPriceIds[0])->first();;
            $give_score = $goods_sku['score'];
            $people     = $goods_sku['people'];
        }else {
            foreach ($orderItemList as $orderItemItem) {
                foreach ($orderItemSkuPrice as $orderItemSkuPriceItem) {
                    if ($orderItemItem->goods_sku_price_id == $orderItemSkuPriceItem->id) {
                        $give_score += ($orderItemSkuPriceItem->score * $orderItemItem->goods_num);
                        $people     += ($orderItemSkuPriceItem->people * $orderItemItem->goods_num);
                        if($people > 0){
                            $peopleInser['member_id']   = $order->member_id;
                            $peopleInser['money']       = $people;
                            $peopleInser['goods_id']    = $orderItemSkuPriceItem->goods_id;
                            $peopleInser['order_id']    = $order->id;
                            $peopleInser['butie_time']  = time()+86400*60;
                            $peopleInser['created_at']  = date('Y-m-d H:i:s');
                            DB::table('member_people')->insert($peopleInser);
                        }
                        break;
                    }
                }
            }
        }
        if ($give_score > 0) {
            $order_user_id = $order->customer_id ?: $order->member_id;
            \memberModel::score($give_score, $order_user_id, 'orderaward', $order->id, '购买商品赠送积分 订单编号' . $order->order_sn);
        }

        if ($people > 0) {
            $order_user_id = $order->customer_id ?: $order->member_id;
            \memberModel::people($people, $order_user_id, 'orderaward', $order->id, '消费补贴 订单编号' . $order->order_sn);
        }

        // 自动发货
        foreach ($orderItemList as $orderItemItem) {
            switch($orderItemItem->dispatch_type){
                case 'selfetch':
                    if ($orderItemItem->goods_type == 'virtual') {
                        // 虚拟商品，核销券，自动发货
                        $this->selfetchSendItem($order, $orderItemItem, ['oper_type' => 'system']);
                    }
                    break;
                case 'autosend':
                    $this->autoSendItem($order, $orderItemItem, ['oper_type' => 'system']);
                    break;
            }
        }

        // 有门店相关的订单
        // $storeIds = [];
        // foreach ($items as $item) {
        //     if (in_array($item['dispatch_type'], ['store', 'selfetch']) && $item['store_id']) {
        //         $storeIds[] = $item['store_id'];
        //     }
        // }

        // $data = [];
        // if ($storeIds) {
        //     $data = [];
        //     // 存在门店，查询门店管理员
        //     $stores = \storeModel::with(['userStore.user'])->whereIn('id', $storeIds)->get();
        //     foreach ($stores as $key => $store) {
        //         $userStoreList = $store['user_store'] ?: [];
        //         unset($store['user_store']);
        //
        //         // 当前门店所有用户管理员
        //         $userList = [];
        //         foreach ($userStoreList as $user) {
        //             if ($user['user']) {
        //                 $userList[] = $user['user'];
        //             }
        //         }
        //
        //         // 有用户才能发送消息
        //         if ($userList) {
        //             $data[] = [
        //                 'store'    => $store,
        //                 'userList' => $userList
        //             ];
        //         }
        //     }
        // }

        // // 存在要通知的门店管理员
        // if ($data) {
        //     // 按门店为单位发送通知
        //     foreach ($data as $key => $sendData) {
        //         \addons\shopro\library\notify\Notify::send(
        //             $sendData['userList'],
        //             new \addons\shopro\notifications\store\Order([
        //                 'store' => $sendData['store'],
        //                 'order' => $order,
        //                 'event' => 'store_order_new'
        //             ])
        //         );
        //     }
        // }

        // 话费充值订单
        if (!empty($order_ext['chongzhi_mobile'])) {
            $mobile = $order_ext['chongzhi_mobile'];
            $data = [
                'out_trade_num' => $order['order_sn'],
                'product_id' => $order_ext['chongzhi_product_id'],
                'mobile' => $mobile,
                'notify_url' => \ChongzhiController::NOTIFYURL,
                'userid' => \ChongzhiController::USERID,
            ];
            $data['sign'] = \ChongzhiController::sign($data);
            $ret = request(\ChongzhiController::CHONGZHIURL, $data);
            \Log::out('Spam话费充值response：' . $ret, 'chongzhi');
            $result = json_decode($ret, true);
            if (isset($result['errno']) && $result['errno'] == 0) {
                $order_ext['chongzhi_remark'] = 'Spam话费充值下单成功';
                $data = [
                    'userid' => \ChongzhiController::USERID,
                    'out_trade_nums' => $result['data']['out_trade_num'],
                ];
                $data['sign'] = \ChongzhiController::sign($data);
                $ret = request(\ChongzhiController::CHECKURL, $data);
                \Log::out('Spam话费充值订单状态查询response：' . $ret, 'chongzhi');
                $result = json_decode($ret, true);
                if (isset($result['errno']) && $result['errno'] == 0 && isset($result['data'][0]['state'])) {
                    $order_ext['chongzhi_state'] = $result['data'][0]['state'];
                }
            } else {
                $order_ext['chongzhi_remark'] = $result['errmsg'] ?? 'Spam话费充值下单失败';
            }
            $order->ext = json_encode($order_ext);
            $order->save();
        }

        \Log::out("order {$order->id} pay success", 'pay');
    }

    /**
     * selfetch 自提/到店 单商品发货
     */
    private function selfetchSendItem($order, $item, $data = [])
    {
        // 获取配送模板
        $dispatch = \dispatchModel::where('type', $item['dispatch_type'])->where('id', $item['dispatch_id'])->first();
        $type_ids = $dispatch['type_ids'] ?? '';
        $dispatch_selfetch_ids = explode(',', $type_ids);

        $dispatchSelfetch = \dispatchselfetchModel::whereIn('id', $dispatch_selfetch_ids)
            ->orderBy('id', 'asc')->first();

        $expiretime = null;       // 核销券过期时间
        if ($dispatchSelfetch) {
            if ($dispatchSelfetch['expire_type'] == 'day') {
                $expire_day = $dispatchSelfetch['expire_day'] > 0 ? $dispatchSelfetch['expire_day'] : 0;
                $expiretime = $expire_day ? (time() + ($expire_day * 86400)) : null;
            } else {
                $expiretime = $dispatchSelfetch['expire_time'] ?: null;
            }
        }

//        if ($item['goods_type'] == 'virtual') {
//            // 商品购买多件，自动生成多个码
//            for ($i = 0; $i < $item['goods_num']; $i++) {
//                $this->createVerify($order, $item, [
//                    'expiretime' => $expiretime
//                ]);
//            }
//        } else {
//            // 商品购买多件，只生成一个码
//            $this->createVerify($order, $item, [
//                'expiretime' => $expiretime
//            ]);
//        }

        $this->sendItem($order, $item, [
            "oper_type" => $data['oper_type'],
        ]);
    }



    /**
     * autosend 单商品自动发货
     */
    private function autoSendItem($order, $item, $data = [])
    {
        // 获取配送模板
        $dispatch = \dispatchModel::where('type', $item['dispatch_type'])->where('id', $item['dispatch_id'])->first();

        $dispatch_autosend_ids = explode(',', $dispatch->type_ids);
        $dispatchAutosend = \dispatchautosendModel::whereIn('id', $dispatch_autosend_ids)
            ->orderBy('id', 'asc')->first();

        $ext = [];
        if ($dispatchAutosend) {
            if (in_array($dispatchAutosend['type'], ['text', 'params'])) {
                $ext['autosend_type'] = $dispatchAutosend['type'];
                $autosend_content = $dispatchAutosend['content'];
                if ($dispatchAutosend['type'] == 'params') {
                    $autosend_content = \dispatchautosendModel::getParamsContent($autosend_content);
                }
                $ext['autosend_content'] = $autosend_content;
            } else if ($dispatchAutosend['type'] == 'card') {
                // 电子卡密，待补充
            }
        }

        $this->sendItem($order, $item, [
            'ext' => $ext,
            "oper_type" => $data['oper_type'],
        ]);
    }

    // 发货
    public function sendItem($order, $item, $data = [])
    {
        $item->express_name = $data['express_name'] ?? null;
        $item->express_code = $data['express_code'] ?? null;
        $item->express_no = $data['express_no'] ?? null;
        $ext = ['send_time' => time()];
        if (isset($data['ext']) && $data['ext']) {
            $ext = array_merge($ext, $data['ext']);
        }
        $item->ext = json_encode($item->setExt($item, $ext));
        $item->dispatch_status = \orderitemModel::DISPATCH_STATUS_SENDED;    // 已发货状态
        $item->save();

        $oper_type = $data['oper_type'] ?? 'system';
        $oper = $data['oper'] ?? 0;
        \orderactionModel::operAdd($order, $item, $oper, $oper_type, '系统自动发货订单');

        // 订单发货后
        $hookData = ['order' => $order, 'item' => $item];
        \Hook::emit('order_send_after', $hookData);
        return $item;
    }

}

